#include "echo.h"

void usage()
{
   printf("Usage: Echo-Server IP  Message\n");
}

int main(int argc, char** argv) 
{
   int sock;

   if (argc < 3) {
      usage();
      return 1;
   }
   if (inet_aton(argv[1], (struct in_addr*)&addr) == -1) {
      usage();
      return 1;
   }
   int client_n = atol(argv[2]);
#ifdef TCP
   if((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
#else
   if((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
#endif
   {
      perror("Socket create: ");
      exit(errno);
   }

   bzero(&addr, sizeof(addr));
   addr.sin_family = AF_INET;
   addr.sin_port = htons(ECHO_PORT);
   #ifdef TCP
   if(connect(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0)
   {
      perror("Couldn't connect to server");
      exit(errno);
   }
   #endif
   size_t msg_len = strlen(argv[2]) + 2;
   char *message = malloc(msg_len);
   strcpy(message, argv[2]);
   //printf("%s", message);
   //message[msg_len - 2] = '\n';
   //message[msg_len - 1] = '\0';

   char buf[strlen(message) + 1];

   write_all(sock, message, strlen(message) + 1);
   read_all(sock, buf, strlen(message) + 1);
   printf("%s\n", buf);
   close(sock);

   return 0;
}
